import axios from 'axios'
import qs from 'qs'
import { Message } from "element-ui";

axios.defaults.timeout = 3000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; 
axios.defaults.baseURL = 'http://127.0.0.1:20000/sys';   //配置接口地址
//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
	//在发送请求之前做某件事
    if(config.method  === 'post'){
        config.data = qs.stringify(config.data);
    }
    return config;
},(error) =>{
    Message({
            showColse: true,
            message: '请求错误',
            type: 'error'
        });
    return Promise.reject(error);
});


//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) =>{
	//对响应数据做些事
     if(response.data.code!=0){
            Message({
                showColse: true,
                message: response.data.errMsg,
                type: 'error'
            })
            return Promise.reject(response);
        }
        return response;
}, (error) => {
     Message({
                showColse: true,
                message: '返回错误',
                type: 'error'
            })
    return Promise.reject(error);
});

function fetch(url,params){
    return new Promise((resolve,reject)=>{
            axios.post(url,params)
            .then(response=>{
                resolve(response.data);
            },err=>{
                reject(err);
            })
            .catch(error=>{
                reject(error)
            })
        });
}

export default {
    fetch
}



